package beautiful.butterfly.distributed_service_container.http.mvc.util.filter;

import beautiful.butterfly.distributed_service_container.http.mvc.http.Request;

import java.io.IOException;
import java.util.Iterator;
import java.util.Set;

public class SqlForbiddenFilter
{
    private static boolean SQLInjectionValidate(String string)
    {
        string = string.toLowerCase();
        // 最后这javascript alert getSession
        // cookie都是为了防止xss漏洞攻击,这个use,update不能加入到上述列表,因为有链接地址中包含是use/update
        final String bad = "exec,execute,insert,create,drop,table,from,grant,group_concat,column_name,"
                + "information_schema.columns,information_schema,columns,table_schema,union,where,select,delete,order,by,count,*,"
                + "chr,mid,master,truncate,char,declare,or,like,1=1,javascript,setCookie,getSession,../";
        String[] badArray = bad.split(",");
        for (int i = 0; i < badArray.length; i++)
        {
            if (string.indexOf(badArray[i]) != -1)
            {
                return true;
            }
        }
        return false;
    }


    @SuppressWarnings("static-access")
    public boolean doFilter(Request request) throws IOException
    {
        // false:表示不符合条件
        Set<String> set = request.getParameterMap().keySet();
        // 表示不符合管理员要求还需继续检测
        Iterator<String> iterator = set.iterator();

        while (iterator.hasNext())
        {
            String name = iterator.next().toString();
            String[] value = (String[]) request.getParameterMap().get(name).toArray();
            for (int i = 0; i < value.length; i++)
            {
                if (SQLInjectionValidate(value[i]) == true)
                {
                    return false;
                }
            }
        }
        return true;

    }

}
